<?php

if( !defined("IN_ELCIUS") ) exit;


$PageData['News'] = array();

// pull news from PHPBB forum
// TODO: phpbb table prefix?
// TODO: redo pretty much all of this
	
if( isset( $Settings['MySQL_host'], $Settings['MySQL_username'], $Settings['MySQL_password'], $Settings['PHPBB_database'] ) ){
	$link = mysqli_connect(
		$Settings['MySQL_host'],
		$Settings['MySQL_username'],
		$Settings['MySQL_password']
	);
}

if ( $link ){
	
	mysqli_select_db( $link, $Settings['PHPBB_database'] );
	
	// find news forum id
	$newsForumId = false;
	$result = mysqli_query( $link, 'SELECT * FROM `phpbb_forums`' );
	while ( $row = mysqli_fetch_array( $result, MYSQL_ASSOC ) ) {
		if( $row['forum_name'] == 'News' ) {
			$newsForumId = $row['forum_id'];
			break;
		}
	}
	mysqli_free_result($result);
	
	// get posts
	$poster_ids = array();
	if( is_numeric( $newsForumId ) ) {
		$result = mysqli_query( $link, 'SELECT * FROM `phpbb_posts` WHERE `forum_id` = '.$newsForumId.' ORDER BY `post_time` DESC' );
		while ( $row = mysqli_fetch_array( $result, MYSQL_ASSOC ) ) {
			if( $row['post_approved'] == 1 && !isset( $PageData['News'][ $row['topic_id'] ] ) ) {
				$poster_ids[] = ($row['poster_id'])*1;
				$PageData['News'][ $row['topic_id'] ] = array( // TODO: validate data
					'ID' => $row['topic_id'],
					'Title' => $row['post_subject'],
					'Added' => $row['post_time'], // TODO: format
					'AddedRelative' => GetRelativeDate( $row['post_time']*1 ),
					'Text' => bb2html( str_replace(':'.$row['bbcode_uid'], '', $row['post_text']), true ),
					'PosterID' => $row['poster_id'],
				);
			}
		}
		mysqli_free_result($result);
	}

	// get names of posters
	$poster_ids = '(`user_id` =\''.implode('\') OR (`user_id` =\'',$poster_ids).'\')';
	$result = mysqli_query( $link, 'SELECT `username`,`user_id` FROM `phpbb_users` WHERE '.$poster_ids);
	$poster_names = array();
	while ( $row = mysqli_fetch_array( $result, MYSQL_ASSOC ) ) {
		$poster_names[$row['user_id']] = $row['username'];
	}

	// insert names into return array
	foreach( $PageData['News'] as $i => $article ){
		if( isset( $poster_names[ $article['PosterID'] ] ) ){
			$PageData['News'][$i]['PosterName'] = $poster_names[ $article['PosterID'] ];
		}
		else{
			$PageData['News'][$i]['PosterName'] = 'Unknown';
		}
	}
	
	mysqli_close( $link );
	
}
else{
	// TODO: mysqli_error( $link );
}

?>